package com.mo.controller;

import com.github.pagehelper.PageInfo;
import com.mo.model.TUser;
import com.mo.query.PasswordQuery;
import com.mo.query.UserQuery;
import com.mo.result.R;
import com.mo.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @author mo
 * version
 */
@RestController
@Slf4j
public class UserController {

    @Resource
    UserService userService;

    @GetMapping("/api/login/info")
    public R loginInfo(Authentication authentication) {
        TUser tuser = (TUser) authentication.getPrincipal();
        return R.OK(tuser);
    }

    @GetMapping("/api/login/free")
    public R freeLogin() {
        return R.OK();
    }

    @PreAuthorize(value = "hasAuthority('user:list')")
    @GetMapping("/api/users")
    public R userPage(@RequestParam(value = "current", required = false) Integer current) {
        if (current == null) {
            current = 1;
        }
        PageInfo<TUser> pageInfo = userService.getUserByPage(current);
        return R.OK(pageInfo);
    }

    @GetMapping("/api/user/{id}")
    @PreAuthorize(value = "hasAuthority('user:view')")
    public R getUserDetailsById(@PathVariable("id") Integer id) {
        TUser user = userService.getUserDetailById(id);
        log.info(user.toString());
        return R.OK(user);
    }

    @PostMapping("/api/user")
    @PreAuthorize(value = "hasAuthority('user:add')")
    public R addUser(UserQuery userQuery) {
        int count = userService.saveUserQuery(userQuery);
        return count >= 1 ? R.OK() : R.FAIL();
    }

    @PutMapping("/api/user")
    public R editUser(UserQuery userQuery) {
        int count = userService.update(userQuery);
        return count >= 1 ? R.OK() : R.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('user:delete')")
    @DeleteMapping("/api/user/{id}")
    public R deleteUser(@PathVariable("id") Integer id) {
        int count = userService.deleteUserById(id);
        return count >= 1 ? R.OK() : R.FAIL();
    }

    @DeleteMapping("/api/user")
    @PreAuthorize(value = "hasAuthority('user:delete')")
    public R batchDelUser(@RequestParam(value = "ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        int batchDel = userService.batchDelUserByIds(idList);
        return batchDel >= idList.size() ? R.OK() : R.FAIL();
    }

    @GetMapping("/api/owners")
    public R owner() {
        List<TUser> ownerList = userService.getOwnerList();
        return R.OK(ownerList);
    }

    @PutMapping("/api/password/change")
    public R changePassword(@RequestBody PasswordQuery passwordQuery){
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String oldPassword = passwordQuery.getOldPassword();
        TUser user = (TUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String originPassword= userService.selectPasswordById(user.getId());
        if(!passwordEncoder.matches(oldPassword,originPassword)){
            return R.OK(499,"原密码不正确");
        }
        String newPassword =passwordEncoder.encode(passwordQuery.getNewPassword()) ;
        user.setLoginPwd(newPassword);
        int update = userService.updatePassword(user);
        return update>=1?R.OK():R.FAIL();
    }
}
